from typing import Annotated
from fastapi import APIRouter, Depends, Request, Body

from sanren.utils import get_current_active_user
from application.http.models import CodeModel
from application.http import schemas


router = APIRouter(prefix='/system/setting', tags=['System'])
module_name = '系统模块'


@router.get('/web-config', response_model=schemas.BaseApiOut)
async def get_web_config(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
):
    """
        网站配置
    """

    site_configs = CodeModel.Setting.where('type', 1).all()

    obj = dict()
    for item in site_configs:
        obj[item.key] = item.value

    return {'data': obj}


@router.post('/web-config', response_model=schemas.BaseApiOut)
async def update_web_config(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    data: dict = Body(),
):
    """
        更新网站配置
    """

    for (key, value) in data.items():
        obj = CodeModel.Setting.where('type', 1).where('key', key).first()
        obj.value = value
        obj.save()

    return {'data': 'ok'}


@router.get('/code-config')
async def get_code_config(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
):
    """
        生码配置
    """

    site_configs = CodeModel.Setting.where('type', 2).all()

    data = dict()
    for item in site_configs:
        data[item.key] = item.value

    # 是否可修改生码配置
    is_edit = 0
    # 判断是否有生码记录
    print(CodeModel.Order.where('status', 2).first() is None)
    if CodeModel.Order.where('status', 2).first() is None:
        is_edit = 1

    return {
        'code': 0,
        'message': 'success',
        'is_edit': is_edit,
        'data': data
    }


@router.post('/code-config', response_model=schemas.BaseApiOut)
async def update_code_config(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    data: dict = Body(),
):
    """
        更新生码配置
    """

    for (key, value) in data.items():
        # 自定义生码批次号
        if key == 'diy_batch_sn':
            # 判断是否有生码记录
            if CodeModel.Order.first() is not None:
                continue

        obj = CodeModel.Setting.where('type', 2).where('key', key).first()
        obj.value = value
        obj.save()

    return {'data': 'ok'}
